import re

from django_redis import get_redis_connection
from rest_framework import serializers
from itsdangerous import TimedJSONWebSignatureSerializer as TJS

from oauth.models import OAuthQQUser
from users.models import User
from rest_framework_jwt.settings import api_settings
from django.conf import settings


class OauthSerializer(serializers.ModelSerializer):
    sms_code = serializers.CharField(max_length=6, min_length=6, write_only=True)
    access_token = serializers.CharField(write_only=True)

    mobile = serializers.CharField(max_length=11, min_length=11)

    token = serializers.CharField(read_only=True)
    username = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ('username','mobile', 'password', 'sms_code', 'access_token','token')
        extra_kwargs = {
            'password': {
                'write_only': True,
                'max_length': 20,
                'min_length': 8
            }
        }
    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$',value):
            raise serializers.ValidationError('手机号格式不匹配')
        return value

    def validate(self, attrs):
        # 短信验证码判断
        conn = get_redis_connection('sms_code')
        real_sms_code = conn.get('sms_code_%s' % attrs['mobile'])
        if real_sms_code is None:
            raise serializers.ValidationError('短信验证码已失效')
        if attrs['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('输入短信验证码错误')

        # access_token 判断
        # 解密
        tjs = TJS(settings.SECRET_KEY,300)
        try:
            data = tjs.loads(attrs['access_token'])
        except:
            raise serializers.ValidationError('错误access_token')

        # 获取openid
        openid = data.get('openid')

        if openid is None:
            raise serializers.ValidationError('无效的access_token')
        attrs['openid'] = openid
        # 查询用户
        try:
            user = User.objects.get(mobile=attrs['mobile'])
        except:
        # 用户不存在
            return attrs
        else:
            if not user.check_password(attrs['password']):
                raise serializers.ValidationError('密码错误')
            attrs['user'] = user
            return attrs

            # 用户存在
    def create(self, validated_data):
        user = validated_data.get('user')
        if user is None:
            user = User.objects.create_user(username=validated_data['mobile'],password=validated_data['password'],mobile=validated_data['mobile'])

        OAuthQQUser.objects.create(user=user, openid=validated_data['openid'])

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user